<script setup lang="ts">
import { reactive, ref } from 'vue';

import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

import DeviceSyncModal from './DeviceSyncModal.vue';
import ImageUploadModal from './ImageUploadModal.vue';

// 接口定义
interface XrayOrder {
  id: string;
  orderName: string;
  petName: string;
  ownerName: string;
  requestDoctor: string;
  createTime: string;
  status: 'completed' | 'pending' | 'processing';
}

interface XrayImage {
  id: string;
  name: string;
  url: string;
  uploadTime: string;
  type: 'photo' | 'sync' | 'upload';
}

interface ReportData {
  examPart: string;
  examDoctor: string;
  examTime: any;
  images: XrayImage[];
  radiographicFindings: string;
  radiographicDiagnosis: string;
  remarks: string;
}

// 响应式数据
const selectedOrder = ref<null | XrayOrder>(null);
const showImageUploadModal = ref(false);
const showDeviceSyncModal = ref(false);

const reportData = reactive<ReportData>({
  examPart: '',
  examDoctor: '',
  examTime: null,
  images: [],
  radiographicFindings: '',
  radiographicDiagnosis: '',
  remarks: '',
});

// 模拟X光检验单数据
const xrayOrders = ref<XrayOrder[]>([
  {
    id: '1',
    orderName: `XR${dayjs().format('YYYYMMDD')}001`,
    petName: '小白',
    ownerName: '张三',
    requestDoctor: '李医生',
    createTime: dayjs().subtract(2, 'hour').format('YYYY-MM-DD HH:mm:ss'),
    status: 'completed',
  },
  {
    id: '2',
    orderName: `XR${dayjs().format('YYYYMMDD')}002`,
    petName: '咪咪',
    ownerName: '李四',
    requestDoctor: '王医生',
    createTime: dayjs().subtract(1, 'hour').format('YYYY-MM-DD HH:mm:ss'),
    status: 'processing',
  },
  {
    id: '3',
    orderName: `XR${dayjs().format('YYYYMMDD')}003`,
    petName: '旺财',
    ownerName: '王五',
    requestDoctor: '张医生',
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    status: 'pending',
  },
]);

// 方法
const createXrayOrder = () => {
  const newOrder: XrayOrder = {
    id: Date.now().toString(),
    orderName: `XR${dayjs().format(
      'YYYYMMDD',
    )}${String(xrayOrders.value.length + 1).padStart(3, '0')}`,
    petName: '新宠物',
    ownerName: '新主人',
    requestDoctor: '当前医生',
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    status: 'pending',
  };

  xrayOrders.value.unshift(newOrder);
  selectOrder(newOrder);
  message.success('X光检验单创建成功！');
};

const selectOrder = (order: XrayOrder) => {
  selectedOrder.value = order;
  // 加载报告数据
  loadReportData(order.id);
};

const loadReportData = (orderId: string) => {
  // 模拟加载报告数据
  if (orderId === '1') {
    reportData.examPart = 'chest';
    reportData.examDoctor = '张技师';
    reportData.examTime = dayjs().subtract(1, 'hour');
    reportData.radiographicFindings =
      '胸部X光片显示肺部纹理清晰，心影大小正常，膈肌位置正常。';
    reportData.radiographicDiagnosis = '胸部X光检查未见明显异常。';
    reportData.remarks = '建议定期复查。';
    reportData.images = [
      {
        id: '1',
        name: '胸部正位片',
        url: 'https://via.placeholder.com/300x400/87CEEB/000000?text=Chest+X-ray',
        uploadTime: dayjs().subtract(1, 'hour').format('YYYY-MM-DD HH:mm:ss'),
        type: 'upload',
      },
    ];
  } else {
    // 重置报告数据
    Object.assign(reportData, {
      examPart: '',
      examDoctor: '',
      examTime: null,
      images: [],
      radiographicFindings: '',
      radiographicDiagnosis: '',
      remarks: '',
    });
  }
};

const uploadImage = () => {
  showImageUploadModal.value = true;
};

const syncFromDevice = () => {
  showDeviceSyncModal.value = true;
};

const takePhoto = () => {
  message.info('实时拍照功能开发中...');
};

const handleImageUploadSuccess = (images: XrayImage[]) => {
  reportData.images.push(...images);
  message.success(`成功上传 ${images.length} 张图片`);
};

const handleDeviceSyncSuccess = (images: XrayImage[]) => {
  reportData.images.push(...images);
  message.success(`成功同步 ${images.length} 张图片`);
};

const removeImage = (index: number) => {
  reportData.images.splice(index, 1);
  message.success('图片已删除');
};

const saveReport = () => {
  if (!selectedOrder.value) {
    message.warning('请先选择检验单');
    return;
  }

  if (!reportData.examPart) {
    message.warning('请选择检查部位');
    return;
  }

  if (!reportData.examDoctor) {
    message.warning('请填写检查医生');
    return;
  }

  if (!reportData.radiographicFindings) {
    message.warning('请填写影像学表现');
    return;
  }

  if (!reportData.radiographicDiagnosis) {
    message.warning('请填写影像学诊断');
    return;
  }

  // 更新检验单状态
  selectedOrder.value.status = 'completed';

  message.success('X光检查报告保存成功！');
};

const printReport = () => {
  message.success('打印功能已触发');
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    pending: 'orange',
    processing: 'blue',
    completed: 'green',
  };
  return colorMap[status] || 'default';
};

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '待检查',
    processing: '检查中',
    completed: '已完成',
  };
  return textMap[status] || status;
};
</script>

<template>
  <div class="xray-management">
    <!-- 左侧：检验单列表 -->
    <div class="left-panel">
      <div class="panel-header">
        <h3>X光检验单</h3>
        <a-button type="primary" size="small" @click="createXrayOrder">
          + 新建检验单
        </a-button>
      </div>

      <div class="order-list">
        <div
          v-for="order in xrayOrders"
          :key="order.id"
          class="order-item"
          :class="{ active: selectedOrder?.id === order.id }"
          @click="selectOrder(order)"
        >
          <div class="order-info">
            <div class="order-name">{{ order.orderName }}</div>
            <div class="pet-info">
              {{ order.petName }}({{ order.ownerName }})
            </div>
            <div class="order-time">{{ order.createTime }}</div>
          </div>
          <div class="order-status">
            <a-tag :color="getStatusColor(order.status)">
              {{ getStatusText(order.status) }}
            </a-tag>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧：检查报告 -->
    <div class="right-panel">
      <div v-if="selectedOrder" class="report-section">
        <div class="report-header">
          <h3>X光检查报告</h3>
          <div class="header-actions">
            <a-button
              type="default"
              @click="printReport"
              style="margin-right: 8px"
            >
              🖨️ 打印
            </a-button>
            <a-button type="primary" @click="saveReport">保存</a-button>
          </div>
        </div>

        <div class="report-form">
          <!-- 基本信息 -->
          <div class="form-section">
            <h4>基本信息</h4>
            <div class="form-grid">
              <div class="form-item">
                <span class="label">检验单号：</span>
                <span class="value">{{ selectedOrder.orderName }}</span>
              </div>
              <div class="form-item">
                <span class="label">宠物名称：</span>
                <span class="value">{{ selectedOrder.petName }}</span>
              </div>
              <div class="form-item">
                <span class="label">主人姓名：</span>
                <span class="value">{{ selectedOrder.ownerName }}</span>
              </div>
              <div class="form-item">
                <span class="label">申请医生：</span>
                <span class="value">{{ selectedOrder.requestDoctor }}</span>
              </div>
            </div>
          </div>

          <!-- 检查信息 -->
          <div class="form-section">
            <h4>检查信息</h4>
            <div class="form-grid">
              <div class="form-item">
                <span class="label">检查部位：</span>
                <a-select
                  v-model:value="reportData.examPart"
                  style="width: 200px"
                  placeholder="请选择检查部位"
                >
                  <a-select-option value="chest">胸部</a-select-option>
                  <a-select-option value="abdomen">腹部</a-select-option>
                  <a-select-option value="spine">脊柱</a-select-option>
                  <a-select-option value="limbs">四肢</a-select-option>
                  <a-select-option value="skull">头颅</a-select-option>
                  <a-select-option value="pelvis">骨盆</a-select-option>
                </a-select>
              </div>
              <div class="form-item">
                <span class="label">检查医生：</span>
                <a-input
                  v-model:value="reportData.examDoctor"
                  style="width: 200px"
                  placeholder="请输入检查医生"
                />
              </div>
              <div class="form-item">
                <span class="label">检查时间：</span>
                <a-date-picker
                  v-model:value="reportData.examTime"
                  show-time
                  style="width: 200px"
                  placeholder="请选择检查时间"
                />
              </div>
            </div>
          </div>

          <!-- X光图片 -->
          <div class="form-section">
            <h4>X光图片</h4>
            <div class="image-upload-section">
              <div class="upload-actions">
                <a-button type="primary" @click="uploadImage">
                  📷 上传X光片
                </a-button>
                <a-button type="default" @click="syncFromDevice">
                  🔄 从设备同步
                </a-button>
                <a-button type="default" @click="takePhoto">
                  📸 实时拍照
                </a-button>
              </div>

              <div class="image-gallery">
                <div
                  v-for="(image, index) in reportData.images"
                  :key="index"
                  class="image-item"
                >
                  <div class="image-container">
                    <img :src="image.url" :alt="image.name" />
                    <div class="image-overlay">
                      <a-button
                        type="text"
                        size="small"
                        danger
                        @click="removeImage(index)"
                      >
                        ×
                      </a-button>
                    </div>
                  </div>
                  <div class="image-info">
                    <div class="image-name">{{ image.name }}</div>
                    <div class="image-time">{{ image.uploadTime }}</div>
                  </div>
                </div>

                <div v-if="reportData.images.length === 0" class="empty-images">
                  <div class="empty-icon">📷</div>
                  <div class="empty-text">暂无X光图片</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 影像学表现 -->
          <div class="form-section">
            <h4>影像学表现</h4>
            <a-textarea
              v-model:value="reportData.radiographicFindings"
              :rows="4"
              placeholder="请描述影像学表现..."
            />
          </div>

          <!-- 影像学诊断 -->
          <div class="form-section">
            <h4>影像学诊断</h4>
            <a-textarea
              v-model:value="reportData.radiographicDiagnosis"
              :rows="4"
              placeholder="请填写影像学诊断..."
            />
          </div>

          <!-- 备注 -->
          <div class="form-section">
            <h4>备注</h4>
            <a-textarea
              v-model:value="reportData.remarks"
              :rows="3"
              placeholder="请填写备注信息..."
            />
          </div>
        </div>
      </div>

      <div v-else class="empty-state">
        <div class="empty-icon">📋</div>
        <div class="empty-text">请选择X光检验单查看报告</div>
      </div>
    </div>

    <!-- 图片上传模态框 -->
    <ImageUploadModal
      :visible="showImageUploadModal"
      @update:visible="showImageUploadModal = $event"
      @success="handleImageUploadSuccess"
    />

    <!-- 设备同步模态框 -->
    <DeviceSyncModal
      :visible="showDeviceSyncModal"
      @update:visible="showDeviceSyncModal = $event"
      @success="handleDeviceSyncSuccess"
    />
  </div>
</template>

<style scoped>
.xray-management {
  display: flex;
  height: 100%;
  background: #f5f5f5;
}

.left-panel {
  display: flex;
  flex-direction: column;
  width: 320px;
  background: white;
  border-right: 1px solid #e8e8e8;
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.order-list {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.order-item {
  padding: 16px;
  margin-bottom: 12px;
  cursor: pointer;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  transition: all 0.3s;
}

.order-item:hover {
  background: #f0f8ff;
  border-color: #1890ff;
}

.order-item.active {
  background: #e6f7ff;
  border-color: #1890ff;
}

.order-info {
  margin-bottom: 8px;
}

.order-name {
  margin-bottom: 4px;
  font-weight: bold;
  color: #333;
}

.pet-info {
  margin-bottom: 4px;
  font-size: 14px;
  color: #666;
}

.order-time {
  font-size: 12px;
  color: #999;
}

.right-panel {
  display: flex;
  flex: 1;
  flex-direction: column;
  background: white;
}

.report-section {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.report-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  border-bottom: 1px solid #e8e8e8;
}

.report-header h3 {
  margin: 0;
  color: #333;
}

.report-form {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 24px;
}

.form-section h4 {
  margin: 0 0 16px;
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.form-item {
  display: flex;
  align-items: center;
}

.form-item .label {
  width: 100px;
  font-size: 14px;
  color: #666;
}

.form-item .value {
  flex: 1;
  font-weight: bold;
  color: #333;
}

.image-upload-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.upload-actions {
  display: flex;
  gap: 8px;
}

.image-gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  min-height: 200px;
}

.image-item {
  overflow: hidden;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.image-container {
  position: relative;
  height: 150px;
  overflow: hidden;
}

.image-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 8px;
  right: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-container:hover .image-overlay {
  opacity: 1;
}

.image-info {
  padding: 8px;
}

.image-name {
  margin-bottom: 4px;
  font-size: 12px;
  color: #333;
}

.image-time {
  font-size: 10px;
  color: #999;
}

.empty-images {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #999;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
}

.empty-icon {
  margin-bottom: 8px;
  font-size: 48px;
}

.empty-text {
  font-size: 14px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.empty-state .empty-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

.empty-state .empty-text {
  font-size: 14px;
}
</style>
